package myapps.myservlet;

import java.io.IOException;
import java.io.PrintWriter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SessionServlet
 */
public class SessionServlet extends HttpServlet {
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SessionServlet() 
	{
		super();
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException 
	{

		String param = req.getParameter("param");
		PrintWriter out = res.getWriter();
		HttpSession session = req.getSession(true);
		
		if (param.equals("getuser")) 
		{
			String user_login = (String) session.getAttribute("user_login");
			
			if (user_login != null) 
			{
				System.out.println(user_login);
				out.print(user_login);
			}
		}
		else if (param.equals("logout")) 
		{
			System.out.println("dang huy session");
			
			// delete record in user_online
			String user_login = (String) session.getAttribute("user_login");
			
			removeOnlineUser(user_login);
			
			// final
			// delete session
			session.invalidate();
			// res.sendRedirect("./index.html");
		}
		else if (param.equals("reload")) 
		{
			session.setAttribute("reading_index", 0);
			System.out.println("reset lai bien session reading_index");
			
		}
		else if (param.equals("leavepage")) // processing like "logout"
		{
						// delete record in user_online
			            System.out.println(" session roi trang roi nhe");
						String user_login = (String) session.getAttribute("user_login");
						
						removeOnlineUser(user_login);
						
						// final
						// delete session
						session.invalidate();			
		}

	}//end post method
    
	/**
	 * remove a user from list of online users
	 * @param username 
	 * @throws IOException
	 */
	public void removeOnlineUser(String username) 
			throws IOException 
	{
		try 
		{
			Class.forName("com.mysql.jdbc.Driver");
			
			Connection connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/chat_group_db", "root", "");
			
			System.out.println(" da ket noi dc database de logout");
			
			Statement statement = connection.createStatement();
			
			statement.executeUpdate("DELETE FROM  user_online WHERE Username = '"
							+ username + "'");
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}

}
